package 反射2;

import sun.swing.StringUIClientPropertyKey;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflectionDemo {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        //1.不适用反射
        Teacher teacher = new Teacher();
        String typelnstanceof=getTypelnstanceof(teacher);
        System.out.println("typelnstanceof = " + typelnstanceof);

        //测试反射方式
        Student student = new Student();
        String type=getType(student);
        System.out.println("type = " + type);
    }
    public static String getTypelnstanceof(Object obj) {
        //学生
        if (obj instanceof Student) {
            Student student = (Student) obj;
            String uSerType = student.getUSerType("王小明");
            return uSerType;
        }
        //老师
        if (obj instanceof Teacher) {
            Teacher teacher = (Teacher) obj;
            String uSerType = teacher.getUserType("王小小");
            return uSerType;
        }
        return null;
    }
    /**
     * 通过反射获取用户的类型
     */
    public static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = obj.getClass();
        Object instance = aClass.newInstance();
        Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke = (String) getUserType.invoke(instance, "王晓晓");
        return invoke;
    }
}
